/**
 *
 */
package com.pocketsweet.ui;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVInstallation;
import com.avos.avoscloud.PushService;
import com.avos.avoscloud.SaveCallback;
import com.easemob.EMCallBack;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.pocketsweet.R;
import com.pocketsweet.C;
import com.pocketsweet.MLApplication;
import com.pocketsweet.MLContext;
import com.pocketsweet.chat.ui.activity.BaseActivity;
import com.pocketsweet.model.MLGallery;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.service.LoginService;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.uilib.ActionSheetDialog;
import com.pocketsweet.ui.uilib.HeaderLayout;
import com.pocketsweet.ui.uilib.LoadingDailog;
import com.pocketsweet.ui.uilib.MyAlertDialog;
import com.pocketsweet.ui.uilib.ActionSheetDialog.OnSheetItemClickListener;
import com.pocketsweet.ui.uilib.ActionSheetDialog.SheetItemColor;
import com.pocketsweet.ui.uilib.HeaderLayout.HeaderStyle;
import com.pocketsweet.ui.uilib.HeaderLayout.onLeftContainerListener;
import com.pocketsweet.ui.uilib.HeaderLayout.onRightContainerListener;
import com.pocketsweet.ui.uilib.wheelcity.WheelView;
import com.pocketsweet.ui.uilib.wheelcity.wheelCity;
import com.pocketsweet.ui.uilib.wheelcity.adapters.ArrayWheelAdapter;
import com.pocketsweet.ui.uilib.wheelview.ScreenInfo;
import com.pocketsweet.ui.uilib.wheelview.WheelMain;
import com.pocketsweet.utils.PhotoUtil;
import com.pocketsweet.utils.StringUtils;
import com.pocketsweet.utils.ToolKits;
import com.pocketsweet.utils.selectPicUtils;

/**
 * @author bobhu
 */
@ContentView(R.layout.activity_register_3)
public class CreateUserInfo extends BaseActivity {
    private static final int REQUEST_CODE_SELECT_PHOTO = 0x01;
    private static final int REQUEST_CROP = 0x02;

    @ViewInject(R.id.etNickname)
    private EditText etNickname;

    @ViewInject(R.id.etSex)
    private TextView etSex;

    @ViewInject(R.id.etBirthday)
    private TextView etBirthday;

    @ViewInject(R.id.etCity)
    private TextView etCity;

    @ViewInject(R.id.etBelong)
    private TextView etBelong;

    @ViewInject(R.id.ivAvatar)
    private ImageView ivAvatar;

    @ViewInject(R.id.linBirthday)
    private LinearLayout linBirthday;

    @ViewInject(R.id.linSex)
    private LinearLayout linSex;

    @ViewInject(R.id.linCity)
    private LinearLayout linCity;

    @ViewInject(R.id.linBelong)
    private LinearLayout linBelong;

    @ViewInject(R.id.mainHeader)
    private HeaderLayout header;

    private AVFile avatar;
    private MLGallery mGallery;
    private Uri cropPath;
    private LoadingDailog mLoadingDialog;
    WheelMain wheelMain;
    private Date brithday = null;
    private String city;
    private String privince;
    private String district;
    private String belong;
    private String nickName;
    private String type;
    int gender = 0;
    private long mExitTime = 0;// 退出事件用到的事件
    private LoginService myLoginSevice;// 友盟第三方登陆service

    final MLUser user = UserService.getCurrentUser();
    private String[] sexList = {"男", "女"};
    private String[] styleFemale = {"软妹萝莉系", "温柔依人系", "阳光治愈系", "知性御姐系",
            "傲娇女王系", "百变全能系"};
    private String[] styleMale = {"小鲜肉系", "高冷型男系", "幽默逗比系", "知心暖男系", "霸道总裁系",
            "百变全能系"};
    private String[] style = {"小鲜肉系", "高冷型男系", "幽默逗比系", "知心暖男系", "霸道总裁系",
            "百变全能系"};
    ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        myLoginSevice = new LoginService(CreateUserInfo.this);
        mLoadingDialog = ToolKits.createLoadingDialog(CreateUserInfo.this,
                "注册中...");
        mLoadingDialog.setText("保存中");
        // user.setGender(gender);
        setHeaderFunction();
        initUserInfo();
    }

    private void initUserInfo() {
        nickName = getIntent().getStringExtra("nickname");
        type = getIntent().getStringExtra("type");
        // gender = Integer.valueOf(getIntent().getStringExtra("gender"));
        // city = getIntent().getStringExtra("location");
        if (!StringUtils.isEmpty(nickName)) {
            etNickname.setText(nickName);
            etNickname.setEms(10);
        }
    }

    public void setHeaderFunction() {
        header = (HeaderLayout) findViewById(R.id.mainHeader);
        header.init(HeaderStyle.IMG_TITLE_TEXT);
        header.setRightText("完成");
        header.setMiddleText("个人信息");
        header.setRighttContainerClickListener(new onRightContainerListener() {
            @Override
            public void onClick() {
                // 注册账号去咯
                // 判断是否有头像
                if (null == avatar) {
                    ToolKits.toast(CreateUserInfo.this, "请上传一个头像");
                    return;
                }

                // 获取当前的用户
                nickName = etNickname.getText().toString();
                String belongString = etBelong.getText().toString();
                if (TextUtils.isEmpty(nickName) || StringUtils.isEmpty(city)
                        || TextUtils.isEmpty(belong) || gender == 0
                        || brithday == null) {
                    ToolKits.toast(CreateUserInfo.this, "请完善您的注册信息");
                    return;
                }
                if (nickName.length() > 16) {
                    ToolKits.toast(CreateUserInfo.this, "昵称不能超过16个字");
                    return;
                }

                mLoadingDialog.show();
                // gender
                user.setLocationCity(city);
                user.setLocationProvince(privince);
                user.setLocationDistrict(district);
                user.setIntro("我们虚拟恋爱吧");

                user.setNickname(ToolKits.replaceBlank(nickName));
                user.setAvatar(avatar);
                user.setGender(gender);
                user.setBirthday(brithday);

                user.setBalance(0);
                user.setPrice(0);
                user.setType(C.USER_TYPE_NORMAL);
                user.setLevel(C.USER_LEVEL_NORMAL);
                user.setStatus(C.USER_STATUS_NORMAL);
                // user.setGold(0);
                user.setBelong(belongString);
                user.setIsInited(1);
                user.setConstellation(ToolKits
                        .getIndexByConstellatinName(ToolKits
                                .constellation(brithday)));
                user.saveInBackground(new SaveCallback() {

                    @Override
                    public void done(AVException e) {
                        if (e != null) {
                            ToolKits.toast(CreateUserInfo.this,
                                    e.getCode() + e.getMessage());
                            mLoadingDialog.dismiss();
                            return;
                        }
                        UserService.getCurrentUser().setSubAvatar(
                                UserService.getCurrentUser().getAvatar()
                                        .getThumbnailUrl(true, 100, 100));
                        UserService.getCurrentUser().saveInBackground(
                                new SaveCallback() {

                                    @Override
                                    public void done(AVException e) {
                                        if (e == null) {
                                            mGallery = new MLGallery();
                                            mGallery.add("images", avatar);
                                            mGallery.setBelongTo(user);
                                            mGallery.saveInBackground(new SaveCallback() { // 再保存照片到MLGallery

                                                @Override
                                                public void done(AVException e) {
                                                    mLoadingDialog.dismiss();
                                                    if (e == null) {
                                                        // 验证通过后注册环信
                                                        myLoginSevice
                                                                .registerHuanxin(type);
                                                    }
                                                }
                                            });

                                        }
                                    }
                                });
                    }
                });
            }
        });
        header.setLeftContainerClickListener(new onLeftContainerListener() {

            @Override
            public void onClick() {
                cancleChannel();
                // 退订之后需要重新保存 Installation
                AVInstallation.getCurrentInstallation().saveInBackground();
                final ProgressDialog pd = new ProgressDialog(
                        CreateUserInfo.this);
                String st = getResources().getString(R.string.Are_logged_out);
                pd.setMessage(st);
                pd.setCanceledOnTouchOutside(false);
                pd.show();
                MLApplication.getInstance().logout(new EMCallBack() {

                    @Override
                    public void onSuccess() {
                        CreateUserInfo.this.runOnUiThread(new Runnable() {
                            public void run() {
                                // 重新显示登陆页面
                                MLUser.logOut();
                                MLContext.deleteAll(); // 删除所有sharepreference
                                pd.dismiss();
                                Intent intent2 = new Intent(
                                        CreateUserInfo.this, Login.class);
                                CreateUserInfo.this.startActivity(intent2);
                                CreateUserInfo.this.finish();
                            }
                        });
                    }

                    @Override
                    public void onProgress(int progress, String status) {

                    }

                    @Override
                    public void onError(int code, String message) {

                    }
                });

            }
        });
    }

    private void cancleChannel() {
        PushService.unsubscribe(CreateUserInfo.this,
                UserService.getCurrentUserId());
        if (UserService.getCurrentUser().getType() == C.USER_TYPE_LOVER
                || UserService.getCurrentUser().getType() == C.USER_TYPE_RECOMMENDED) {
            if (UserService.getCurrentUser().getGender() == C.USER_GENDER_MALE) {
                PushService.unsubscribe(CreateUserInfo.this, "SweetMale");
            } else if (UserService.getCurrentUser().getGender() == C.USER_GENDER_FEMALE) {
                PushService.unsubscribe(CreateUserInfo.this, "SweetFemale");
            }
        }

    }

    @OnClick(R.id.ivAvatar)
    public void onAvatarClick(View view) {
        // 从系统相册中选择一张照片作为头像
        new ActionSheetDialog(CreateUserInfo.this)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("从相册选择", SheetItemColor.Gray,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                Intent intent = new Intent();
                                intent.setDataAndType(
                                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                        "image/*");
                                intent.setAction(Intent.ACTION_GET_CONTENT);
                                startActivityForResult(intent,
                                        REQUEST_CODE_SELECT_PHOTO);
                                // selectPicUtils.openLocalImage(getActivity());
                            }
                        })
                .addSheetItem("拍照", SheetItemColor.Gray,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                selectPicUtils
                                        .openCameraImage(CreateUserInfo.this);
                            }
                        }).show();
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 600);
        intent.putExtra("outputY", 600);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cropPath);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);
        startActivityForResult(intent, REQUEST_CROP);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_CANCELED) {
            return;
        }
        switch (requestCode) {
            case selectPicUtils.GET_IMAGE_BY_CAMERA: // 拍照上传
                Uri url = selectPicUtils.imageUriFromCamera;
                if (url != null) {
                    String sImagePath = ToolKits.getImgRealPathFromURI(url,
                            CreateUserInfo.this);
                    String copressPath = sImagePath + "_small";
                    WindowManager wm = (WindowManager) CreateUserInfo.this
                            .getSystemService(Context.WINDOW_SERVICE);
                    int width = wm.getDefaultDisplay().getWidth();
                    selectPicUtils.cropBgImage(CreateUserInfo.this,
                            selectPicUtils.imageUriFromCamera, 1, 1, 600, 600);
                }
                break;
            case REQUEST_CODE_SELECT_PHOTO: // 选择图片上传,每次上传一个图片，就会上传到服务器,但是未保存到MLUser

                if (null != data) {
                    Uri url1 = data.getData();
                    String ImagePath = ToolKits.getImgRealPathFromURI(url1,
                            CreateUserInfo.this);
                    File file = new File(ImagePath);
                    cropPath = Uri.parse("file://" + file.getAbsolutePath()
                            + "_small");
                    startPhotoZoom(Uri.fromFile(file));
                }
                break;
            case selectPicUtils.CROP_IMAGE: // 拍照后的回调
                if (selectPicUtils.cropImageUri != null) {
                    File avatarCrop = selectPicUtils.createFileFromUri(
                            selectPicUtils.cropImageUri, CreateUserInfo.this);
                    UserService.displayAvatar(
                            "file://" + avatarCrop.getAbsolutePath(), ivAvatar);
                    try {
                        String copressPath = avatarCrop.getAbsolutePath()
                                + "_small";
                        PhotoUtil.compressImage(avatarCrop.getAbsolutePath(),
                                copressPath);
                        avatar = AVFile.withAbsoluteLocalPath(avatarCrop.getName(),
                                copressPath);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case REQUEST_CROP: // 选择图片后的回调
                if (cropPath == null) {
                    return;
                }
                String ImagePath = ToolKits.getImgRealPathFromURI(cropPath,
                        CreateUserInfo.this);
                String copressPath = ImagePath + "_small";
                PhotoUtil.compressImage(ImagePath, copressPath);
                File file = new File(copressPath);
                if (file.exists()) {
                    try {
                        avatar = AVFile.withAbsoluteLocalPath(file.getName(),
                                file.getAbsolutePath());
                        UserService.displayAvatar(
                                "file://" + file.getAbsolutePath(), ivAvatar);
                        // mGalleryView.addImagePath(ImagePath);// 先显示图片，不上传
                        // mAVFileList.add(photo);

                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToolKits.toast(CreateUserInfo.this, "文件不存在！");
                }
            default:
                break;
        }
        if (requestCode == REQUEST_CODE_SELECT_PHOTO) {

        }
    }

    @OnClick(R.id.linBirthday)
    public void onDateClick(View view) {
        LayoutInflater inflater1 = LayoutInflater.from(CreateUserInfo.this);
        final View timepickerview1 = inflater1.inflate(R.layout.timepicker,
                null);
        ScreenInfo screenInfo1 = new ScreenInfo(CreateUserInfo.this);
        wheelMain = new WheelMain(timepickerview1);
        wheelMain.screenheight = screenInfo1.getHeight();
        Calendar calendar1 = Calendar.getInstance();
        int year1 = calendar1.get(Calendar.YEAR);
        int month1 = calendar1.get(Calendar.MONTH);
        int day1 = calendar1.get(Calendar.DAY_OF_MONTH);
        wheelMain.initDateTimePicker(year1, month1, day1);
        final MyAlertDialog dialog = new MyAlertDialog(CreateUserInfo.this)
                .builder().setTitle("生日选择").setView(timepickerview1)
                .setNegativeButton("取消", new OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });
        dialog.setPositiveButton("确定", new OnClickListener() {
            @SuppressLint("SimpleDateFormat")
            @Override
            public void onClick(View v) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    brithday = sdf.parse(wheelMain.getTime());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                etBirthday.setText(format.format(brithday));
                etBirthday.setTextColor(getResources().getColor(
                        R.color.text_666));
            }
        });
        dialog.show();
    }

    @OnClick(R.id.linSex)
    public void onSexClick(View view) {
        View sexView = LayoutInflater.from(this).inflate(
                R.layout.wheelcity_cities_layout, null);
        final WheelView sexWheel = (WheelView) sexView
                .findViewById(R.id.wheelcity_city);
        WheelView wheelcity_country = (WheelView) sexView
                .findViewById(R.id.wheelcity_country);
        WheelView wheelcity_ccity = (WheelView) sexView
                .findViewById(R.id.wheelcity_ccity);
        wheelcity_ccity.setVisibility(View.GONE);
        wheelcity_country.setVisibility(View.GONE);
        ArrayWheelAdapter<String> adapter = new ArrayWheelAdapter<String>(this,
                sexList);
        adapter.setTextSize(18);
        sexWheel.setViewAdapter(adapter);
        sexWheel.setCurrentItem(0);
        final MyAlertDialog dialog = new MyAlertDialog(CreateUserInfo.this)
                .builder().setTitle("性别选择").setView(sexView)
                .setNegativeButton("取消", new OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });
        dialog.setPositiveButton("确定", new OnClickListener() {
            @Override
            public void onClick(View v) {
                etSex.setText(sexList[sexWheel.getCurrentItem()]);
                etSex.setTextColor(getResources().getColor(R.color.text_666));
                gender = sexWheel.getCurrentItem() + 1;
            }
        });
        dialog.show();
    }

    @OnClick(R.id.linCity)
    public void onCityClick(View view) {
        final wheelCity myWheelCity = new wheelCity(CreateUserInfo.this);
        View cityview = myWheelCity.getView();
        final MyAlertDialog dialog1 = new MyAlertDialog(CreateUserInfo.this)
                .builder().setTitle("城市选择").setView(cityview)
                .setNegativeButton("取消", new OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });
        dialog1.setPositiveButton("确定", new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (myWheelCity.getProvinceText().equals("未设定")
                        || myWheelCity.getCityText().equals("未设定")) {
                    Toast.makeText(CreateUserInfo.this, "您还未选择城市", 1).show();
                    return;
                }

                if (!myWheelCity.getProvinceText().equals("未设定")) {
                    privince = myWheelCity.getProvinceText();
                    // mlUser.setLocationProvince(myWheelCity
                    // .getProvinceText());
                    // location = myWheelCity.getProvinceText();
                }
                if (!myWheelCity.getCityText().equals("未设定")) {
                    city = myWheelCity.getCityText();
                    etCity.setText(city);
                    etCity.setTextColor(getResources().getColor(
                            R.color.text_666));
                    // mlUser.setLocationCity(myWheelCity.getCityText());
                    // location = myWheelCity.getCityText();
                }
                // if (!myWheelCity.getCountryText().equals("未设定")) {
                // district = myWheelCity.getCountryText();
                // mlUser.setLocationDistrict(myWheelCity.getCountryText());
                // }
                // mlUser.saveInBackground(new SaveCallback() {
                //
                // @Override
                // public void done(AVException e) {
                // if (e == null) {
                // Log.e("==成功", "保存城市成功");
                // tvCity.setText(location);
                //
                // } else {
                // Log.e("==error", "保存城市错误");
                // }
                // }
                // });
                // Toast.makeText(getActivity(), "保存成功", 1).show();

            }
        });
        dialog1.show();

    }

    @OnClick(R.id.linBelong)
    public void clickBelong(View view) {
        if (gender == 0) {
            ToolKits.toast(CreateUserInfo.this, "您还没选择性别");
            return;
        } else {
            if (gender == 1) {
                style = styleMale;
            } else {
                style = styleFemale;
            }
        }
        View belongView = LayoutInflater.from(this).inflate(
                R.layout.wheelcity_cities_layout, null);
        final WheelView belongWheel = (WheelView) belongView
                .findViewById(R.id.wheelcity_city);
        WheelView wheelcity_country = (WheelView) belongView
                .findViewById(R.id.wheelcity_country);
        WheelView wheelcity_ccity = (WheelView) belongView
                .findViewById(R.id.wheelcity_ccity);
        wheelcity_ccity.setVisibility(View.GONE);
        wheelcity_country.setVisibility(View.GONE);
        ArrayWheelAdapter<String> adapter = new ArrayWheelAdapter<String>(this,
                style);
        adapter.setTextSize(18);
        belongWheel.setViewAdapter(adapter);
        belongWheel.setCurrentItem(0);
        final MyAlertDialog dialog = new MyAlertDialog(CreateUserInfo.this)
                .builder().setTitle("我属于").setView(belongView)
                .setNegativeButton("取消", new OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });
        dialog.setPositiveButton("确定", new OnClickListener() {
            @Override
            public void onClick(View v) {
                belong = style[belongWheel.getCurrentItem()];
                etBelong.setText(belong);
                etBelong.setTextColor(getResources().getColor(R.color.text_666));
            }
        });
        dialog.show();
    }

    /**
     * 重写onKeyDown方法
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            showExitAlet();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showExitAlet() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Toast toast = Toast.makeText(CreateUserInfo.this, "再按一次退出程序",
                    Toast.LENGTH_LONG);
            // 可以控制toast显示的位置
            toast.setGravity(Gravity.BOTTOM, 0, 150);
            toast.show();
            mExitTime = System.currentTimeMillis();

        } else {
            CreateUserInfo.this.finish();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }
}
